/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package work.thread_eg.pool;

import cn.hutool.core.date.DateUtil;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 * 使用 ThreadPoolExecutor创建自定义线程池
 *
 */
public class ThreadPoolExecutorMain {

    public static void main(String[] args) {
        // 使用ThreadPoolExecutor创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                5, 10, 200, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(5));

        // 创建任务
        for (int i = 0; i < 15; i++) {
            MyTask myTask = new MyTask(i);
            executor.execute(myTask);
            System.out.println("线程池中线程数目：" + executor.getPoolSize() + "，队列中等待执行的任务数目：" +
                    executor.getQueue().size() + "，已执行玩别的任务数目：" + executor.getCompletedTaskCount());
        }

        // 关闭线程池
        executor.shutdown();
    }

    public static void sleep(int time)  {
        try {
            Thread.sleep(time);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class MyTask implements Runnable {
        private int taskNum;

        public MyTask(int num) {
            this.taskNum = num;
        }

        @Override
        public void run() {
            String info0 = DateUtil.now() + " " + Thread.currentThread().getName();
            System.out.println(info0 + ":" + "正在执行task " + taskNum);
            try {
                Thread.currentThread().sleep(4000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String info = DateUtil.now() + " " + Thread.currentThread().getName();
            System.out.println(info + ":" + "task " + taskNum + "执行完毕");
        }
    }
}


